/**
 * 
 */
package com.ld.tamp.web.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ld.tamp.web.bean.AuthorizerInfo;
import com.ld.tamp.web.bean.AuthorizerJsTicket;

import weixin.popular.bean.component.AuthorizerAccessToken;
import weixin.popular.bean.ticket.Ticket;

/**
 * @author KeYang
 *
 */
@Component
public class AuthorizerJsTicketDao {

	private static final String AUTHORIZER_JS_TICKET = "Authorizer_Js_Ticket";

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	public void save(String appid, Ticket ticket) {
		AuthorizerJsTicket authorizerJsTicket = new AuthorizerJsTicket(appid, ticket);
		redisTemplate.opsForHash().put(AUTHORIZER_JS_TICKET, appid, JSON.toJSONString(authorizerJsTicket));
	}

	public AuthorizerJsTicket read(String appid) {
		String authorizerJsTicketJson = (String) redisTemplate.opsForHash().get(AUTHORIZER_JS_TICKET, appid);
		AuthorizerJsTicket AuthorizerJsTicket = JSON.parseObject(authorizerJsTicketJson, AuthorizerJsTicket.class);
		return AuthorizerJsTicket;
	}

	public Map<String, AuthorizerJsTicket> readEntries() {

		Map<String, AuthorizerJsTicket> result = new HashMap<String, AuthorizerJsTicket>();
		Map<Object, Object> map = redisTemplate.opsForHash().entries(AUTHORIZER_JS_TICKET);
		Iterator<Entry<Object, Object>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<Object, Object> entry = iterator.next();
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			AuthorizerJsTicket AuthorizerJsTicket = JSON.parseObject(value, AuthorizerJsTicket.class);
			result.put(key, AuthorizerJsTicket);
		}
		return result;
	}

	/**
	 * @param authorizer_appid
	 * @param authorizerJsTicket
	 */
	public void update(String authorizerAppid, Ticket ticket) {
		AuthorizerJsTicket authorizerJsTicket = read(authorizerAppid);
		if(authorizerJsTicket!=null){
			authorizerJsTicket.setTicket(ticket.getTicket());
			authorizerJsTicket.setExpireTime(ticket.getExpires_in()*1000+System.currentTimeMillis());
			redisTemplate.opsForHash().put(AUTHORIZER_JS_TICKET, authorizerAppid, JSON.toJSONString(authorizerJsTicket));
		}else{
			save(authorizerAppid,ticket);
		}
	}

}